package com.hengxinguotong.zhihuichengjian.ui.security;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.DatePicker;
import android.widget.RelativeLayout;
import android.widget.TimePicker;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AccidentAddPersonAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Safety;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.AddPersonnelActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.PersonnelActivity;
import com.hengxinguotong.zhihuichengjian.ui.SearchPersonActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;


/**
 * 安全演习  安全培训
 * Created by liux on 2017/3/7.
 */

public class SafetyDrillActivity extends BaseActivity implements AualityTestAddPicAdapter.OnRecyclerViewClickListener {
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_test)
    HXTextView saveTest;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.theme_etv)
    HXEditTextView themeEtv;
    @BindView(R.id.starttime_tv)
    HXTextView starttimeTv;
    @BindView(R.id.position_rl)
    RelativeLayout positionRl;
    @BindView(R.id.endtime_etv)
    HXTextView endtimeEtv;
    @BindView(R.id.profession_rl)
    RelativeLayout professionRl;
    @BindView(R.id.charger_tv)
    HXTextView chargerTv;
    @BindView(R.id.charger_rl)
    RelativeLayout chargerRl;
    @BindView(R.id.lecturer_etv)
    HXEditTextView lecturerEtv;
    @BindView(R.id.lecturer_rl)
    RelativeLayout lecturerRl;
    @BindView(R.id.address_title_tv)
    HXTextView addressTitleTv;
    @BindView(R.id.address_etv)
    HXEditTextView addressEtv;
    @BindView(R.id.injured_title)
    HXTextView injuredTitle;
    @BindView(R.id.no_injured_tv)
    HXTextView noInjuredTv;
    @BindView(R.id.join_person_rv)
    RecyclerView joinPersonRv;
    @BindView(R.id.no_pic_tv)
    HXTextView noPicTv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;
    @BindView(R.id.remark_etv)
    HXEditTextView remarkEtv;
    private AualityTestAddPicAdapter aualityTestAddPicAdapter;
    private AccidentAddPersonAdapter joinInAdapter;

    private List<String> paths;
    private List<String> minPaths;
    private List<User> joinInUsers;
    private AlertDialog dialog;

    private int type = 1;//1 安全培训  2安全演习
    private String interfaceString;
    private Safety safety;
    private String personId;
    private final int SELECTPERSON = 1001;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_safe_drill);
        type = getIntent().getIntExtra("type", Constants.SAFETY_TRAINING);
        safety = (Safety) getIntent().getSerializableExtra("safety");
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        switch (type) {
            case Constants.SAFETY_TRAINING:
                tvTitleName.setText("安全培训");
                addressTitleTv.setText("培训地点");
                break;
            case Constants.SAFETY_DRILL:
                tvTitleName.setText("安全演习");
                addressTitleTv.setText("演习地点");
                lecturerRl.setVisibility(View.GONE);
                break;
        }


        if (safety != null) {
            Utils.setEditTextViewUnable(safety.getTheme(), themeEtv);
            Utils.setEditTextViewUnable(safety.getStartDate(), starttimeTv);
            Utils.setEditTextViewUnable(safety.getEndDate(), endtimeEtv);
            Utils.setEditTextViewUnable(safety.getContactPerson(), lecturerEtv);
            Utils.setEditTextViewUnable(safety.getPlace(), addressEtv);
            Utils.setEditTextViewUnable(safety.getRemark(), remarkEtv);
            if (type == 2) {
                Utils.setEditTextViewUnable(safety.getContactPerson(), chargerTv);
            }
            saveTest.setVisibility(View.GONE);

            if (safety.getPicList().size() == 0) {
                noPicTv.setVisibility(View.VISIBLE);
            } else {
                paths = safety.getPicList();
                aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, false);
                addPicRv.setLayoutManager(getLinearLayoutManager());
                addPicRv.setAdapter(aualityTestAddPicAdapter);
            }
            if (safety.getPersonList().size() == 0) {
                noInjuredTv.setVisibility(View.VISIBLE);
            } else {
                joinInAdapter = new AccidentAddPersonAdapter(this, safety.getPersonList(), new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        Intent intent = new Intent(SafetyDrillActivity.this, AddPersonnelActivity.class);
                        intent.putExtra("type", AddPersonnelActivity.MODTYPE);
                        intent.putExtra("personId", safety.getPersonList().get(position).getPersonId());
                        startActivity(intent);
                    }

                    @Override
                    public void onClick(View v) {

                    }
                }, false);
                joinPersonRv.setLayoutManager(getLinearLayoutManager());
                joinPersonRv.setAdapter(joinInAdapter);
            }
        } else {
            paths = new ArrayList<String>();
            paths.add(Utils.ADDPIC);
            aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
            addPicRv.setLayoutManager(getLinearLayoutManager());
            addPicRv.setAdapter(aualityTestAddPicAdapter);
            joinInUsers = new ArrayList<User>();
            joinInUsers.add(getAddUser());
            joinInAdapter = new AccidentAddPersonAdapter(this, joinInUsers, new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                @Override
                public void onItemClick(View v, int position) {
                    if (joinInUsers.get(position).getHeadPortrait() != null && Utils.ADDPIC.equals(joinInUsers.get(position).getHeadPortrait())) {
                        Intent intent = new Intent(SafetyDrillActivity.this, SearchPersonActivity.class);
                        intent.putExtra("selectUsers", (Serializable) joinInUsers);
                        startActivityForResult(intent, 2);
                    } else {
                        joinInUsers.remove(position);
                        joinInAdapter.notifyDataSetChanged();
                    }

                }

                @Override
                public void onClick(View v) {

                }
            }, true);

            joinPersonRv.setLayoutManager(getLinearLayoutManager());
            joinPersonRv.setAdapter(joinInAdapter);

        }

    }

    private void getMinImage() {
        if (!checkContent()) {
            return;
        }

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    addTest();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            addTest();
        }

    }

    private void showDatePickerDialog(final int timeType) {
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        showTimePickerDialog(timeType, year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();


    }


    private void showTimePickerDialog(final int timeType, final String date) {
        Calendar c = Calendar.getInstance();
        new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                if (timeType == 1) {
                    starttimeTv.setText(date + " " + hourOfDay + ":" + minute);
                } else {
                    endtimeEtv.setText(date + " " + hourOfDay + ":" + minute);
                }

            }
        }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {
            paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            paths.add(Utils.ADDPIC);
            if (aualityTestAddPicAdapter != null) {
                aualityTestAddPicAdapter.setPaths(paths);
            }
        } else if (requestCode == 2 && data != null) {
            List<User> temp = (List<User>) data.getSerializableExtra("selectUsers");
            for (int i = 0; i < temp.size(); i++) {
                User user = temp.get(i);
                if (!user.isInUsers(joinInUsers)) {
                    joinInUsers.add(0, user);
                }
            }
            joinInAdapter.notifyDataSetChanged();
        } else if (requestCode == SELECTPERSON && data != null) {
            List<User> temp = (List<User>) data.getSerializableExtra("selectUsers");
            if (temp.size() == 1) {
                personId = temp.get(0).getPersonId();
                chargerTv.setText(temp.get(0).getName());
            }
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            if (safety != null) {
                TaskBigImgActivity.startActivity(SafetyDrillActivity.this, (ArrayList<String>) paths, position);
            } else {
                paths.remove(position);
                aualityTestAddPicAdapter.notifyDataSetChanged();
            }
        }
    }


    private void addTest() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("constructionId", SPUtil.getString(this,"constructionid"));
        params.addBodyParameter("type", type + "");
        params.addBodyParameter("startDate", starttimeTv.getText().toString());
        params.addBodyParameter("endDate", endtimeEtv.getText().toString());
        params.addBodyParameter("theme", themeEtv.getEditableText().toString());
        params.addBodyParameter("place", addressEtv.getEditableText().toString());
        if (type == 1) {
            params.addBodyParameter("contactPerson", lecturerEtv.getEditableText().toString());
        }

        params.addBodyParameter("remark", remarkEtv.getEditableText().toString());
        for (int i = 0; i < minPaths.size(); i++) {
            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
        }

        if (joinInUsers != null && joinInUsers.size() != 0) {
            for (int i = 0; i < joinInUsers.size() - 1; i++) {
                params.addBodyParameter("personIds[" + i + "]", joinInUsers.get(i).getPersonId());
            }
        }

        Utils.requestData(getResources().getString(R.string.loading), this, "/safeStudy/save/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                showToast("提交成功");
                setResult(1);
                finish();
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }


    private boolean checkContent() {
        if (Utils.isEmpty(themeEtv.getEditableText().toString())) {
            showToast("请填写主题");
            return false;
        }
        if (Utils.isEmpty(starttimeTv.getText().toString())) {
            showToast("请选择开始时间");
            return false;
        }
        if (Utils.isEmpty(endtimeEtv.getText().toString())) {
            showToast("请选择结束时间");
            return false;
        }

        if (type == 1) {
            if (Utils.isEmpty(lecturerEtv.getEditableText().toString())) {
                showToast("请填写讲师姓名");
                return false;
            }
        }

        if (Utils.isEmpty(addressEtv.getEditableText().toString())) {
            showToast("请填写地点");
            return false;
        }

        return true;

    }

    private User getAddUser() {
        User addUser = new User();
        addUser.setHeadPortrait(Utils.ADDPIC);
        addUser.setPersonId("-1");
        addUser.setName("");
        return addUser;
    }

    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }

    @OnClick({R.id.iv_back, R.id.save_test, R.id.starttime_tv, R.id.endtime_etv, R.id.charger_rl})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_test:
                getMinImage();
                break;
            case R.id.starttime_tv:
                showDatePickerDialog(1);
                break;
            case R.id.endtime_etv:
                showDatePickerDialog(2);
                break;
            case R.id.charger_rl:
                intent = new Intent(this, SearchPersonActivity.class);
                intent.putExtra("isone", true);
                startActivityForResult(intent, SELECTPERSON);
                break;
        }
    }

}
